package com.sais.manage.boot.platform.utils;


import com.google.code.kaptcha.Constants;
import com.sais.manage.boot.platform.dto.LoginDTO;
import com.sais.manage.boot.platform.exception.BusinessException;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 宿舍管理系统-验证码 校验
 *
 * @author zwp
 * @date 2020/02/25
 **/
public class KapUtils {
    private static volatile KapUtils kapUtils = null;

    private KapUtils() {
    }

    public static KapUtils getKapUtils() {
        if (kapUtils == null) {
            synchronized (KapUtils.class) {
                if (kapUtils == null) {
                    kapUtils = new KapUtils();
                }
            }
        }
        return kapUtils;
    }


    public static boolean verifyKap(LoginDTO loginDTO, HttpServletRequest request) {
        String dtoKap = loginDTO.getKaptcha();
        if (StringUtils.isEmpty(dtoKap)) {
            throw new BusinessException(BusinessException.KAPTCHA_NO);
        }
        //获取当前session中验证码数字，和登录时用户输入的做对比
        HttpSession session = request.getSession();
        String kap = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);

        if (dtoKap.equals(kap)) {
            return true;
        }
        return false;
    }

}
